<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-下脚料入库单`"
		width="960px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="flex-start-center margin-bottom-4" style="font-size: 13px;">
					<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div v-else style="font-size: 16px;">
						<span class="el-icon-star-off item-gap"></span>
						<span>{{ ruleForm.code || '系统自动生成' }}</span>
					</div>
				</div>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.workshopName }}</span>
								<jk-select v-else v-model="ruleForm.workshopId" class="width-100-percent" size="medium" :option-list="workshopList" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="日期" prop="minValue">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="仓库" prop="minValue">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-select v-else v-model="ruleForm.belongDa3te" class="width-100-percent" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="出库类别" prop="minValue">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-select v-else v-model="ruleForm.belongDate2" class="width-100-percent" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="部门" prop="minValue">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-select v-else v-model="ruleForm.belongDat3e" class="width-100-percent" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<el-button class="margin-bottom-4 margin-top-10" icon="el-icon-plus" size="mini" type="primary">物料明细</el-button>
			</div>
			<jk-table border :data="ruleForm.configItem" :height="dialogTableHeight - 20">
				<vxe-column title="操作" align="center" field="operation" :width="70">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-minus" @click="ruleForm.configItem.splice(scope.rowIndex, 1)" />
						</div>
					</template>
				</vxe-column>
				<vxe-column title="物料" align="left" field="unitPrice" :min-width="100"></vxe-column>
				<vxe-column title="批号" align="left" field="unitPrice" :min-width="120"></vxe-column>
				<vxe-column title="单位" align="left" field="unitPrice" :width="70"></vxe-column>
				<vxe-column title="重量" align="right" field="unitPrice" :width="100">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.bcrk }}</span>
						<jk-number-input v-else v-model="scope.row.bcrk" size="mini" placeholder="" />
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { spinYarnCountPriceConfigCreate, spinYarnCountPriceConfigUpdate, spinYarnCountPriceConfigGet } from '../../../api/material/yarnCounPrice';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input';
    import { formatDate } from '../../../utils/jk/jk-tool';
    export default {
        mixins: [calHeight],
        components: { remoteSearchProductInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'minValue': null,
                    'maxValue': null,
                    'auditState': 0,
                    'remark': '',
                    'configItem': [
                        { orderCode: 'MO20240422001', bgsl: 200, drk: 100, saleOrderCode: 'SO202404220021', bcrk: 50 },
                        { orderCode: 'MO20240422001', bgsl: 200, drk: 100, saleOrderCode: 'SO202404220023', bcrk: 50 },
                        { orderCode: 'MO20240422002', bgsl: 200, drk: 120, saleOrderCode: 'SO202404220025', bcrk: 60 },
                        { orderCode: 'MO20240422002', bgsl: 200, drk: 120, saleOrderCode: 'SO202404220027', bcrk: 60 }
                    ]
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    maxValue: [{ required: true, trigger: 'change' }],
                    criterion: [{ required: true, trigger: 'change' }],
                    tenPrice: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': 0
                }
            };
        },
        methods: {
            onDeleteBtn(scope) {
                this.ruleForm.configItem.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.configItem.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? spinYarnCountPriceConfigCreate : spinYarnCountPriceConfigUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinYarnCountPriceConfigGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.configItem = resData.configItem || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
